package com.ls.blog.security.meta;

import com.ls.blog.dto.ResourceDTO;
import com.ls.blog.security.handler.CustomizeAccessDeniedHandler;
import com.ls.blog.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 权限拦截器数据源
 */
@Component
public class CustomizeFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private CustomizeAccessDeniedHandler customizeAccessDeniedHandler;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求地址
        String requestUrl = ((FilterInvocation) o).getRequest().getRequestURI();
        // 获取用户请求方式
        String method = ((FilterInvocation) o).getRequest().getMethod();
        List<ResourceDTO> resourceDTOList = resourceService.listResourceDTO();
        //查询具体某个接口的角色列表
        for (ResourceDTO resourceDTO :resourceDTOList) {
            if (Objects.isNull(resourceDTO.getUrl())){
                continue;
            }
            if (antPathMatcher.match(resourceDTO.getUrl(), requestUrl)&&method.equals(resourceDTO.getRequestMethod())){
                List<String> roleCodeList = resourceDTO.getRoleCodeList();
                if (CollectionUtils.isEmpty(roleCodeList)) {
                    // 没有角色直接拒绝
                    return SecurityConfig.createList("disable");
                }
                return SecurityConfig.createList(roleCodeList.toArray(new String[]{}));
            }
        }
        // 匿名接口直接放行
        return null;
    }




    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
